package com.jinyi.wwdeng.ui.main.fragment

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.jinyi.base.utils.BarUtils
import com.jinyi.lib_baseadapter.BGAOnItemChildClickListener
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.FragmentCreditRepaymentBinding
import com.jinyi.wwdeng.pro.ProMvpFragment
import com.jinyi.wwdeng.ui.main.adapter.CreditRepaymentLableAdapter
import com.jinyi.wwdeng.ui.main.contract.CreditRepaymentContract
import com.jinyi.wwdeng.ui.main.impl.CreditRepaymentPresenterImpl
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.ui.user.fragment.UserFragment
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import com.jinyi.wwdeng.utils.recyclerview.LinearSpacingItemDecoration
import org.json.JSONObject


/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/24 16:04
 * @Annotation：贷款还款
 */
class CreditRepaymentFragment: ProMvpFragment<CreditRepaymentContract.View, CreditRepaymentPresenterImpl>(), CreditRepaymentContract.View {

    lateinit var binding: FragmentCreditRepaymentBinding

    //还款明细
    private var mLableAdapter: CreditRepaymentLableAdapter? = null
    //是否展开
    private var isOpen = false

    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentCreditRepaymentBinding.inflate(inflater)
        return binding.root
    }

    override fun createPresenter(): CreditRepaymentPresenterImpl {
        return CreditRepaymentPresenterImpl()
    }

    override fun initView() {
        binding.parentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        binding.tvTitle.text = getString(R.string.app_name)

        //添加侧边个人中心
        addMenuFragment()

        initRefreshLayout()
        initRecyclerView()
        showOpenOrCloseView()
    }

    override fun initListener() {
        //个人中心
        binding.ivAvatar.setOnClickListener {
            var isOpen = binding.drawerLayout.isDrawerOpen(GravityCompat.START)
            if (isOpen){//是否打开
                binding.drawerLayout.closeDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditRepayment Page Close")
            } else {
                binding.drawerLayout.openDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditRepayment Page Open")
            }
        }
        //客服
        binding.ivKefu.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"CreditRepayment Page")
        }
        //展开、收起
        binding.ivLable.setOnClickListener {
            isOpen = !isOpen
            showOpenOrCloseView()
        }
        //还款
        binding.btnRepayment.setOnClickListener {
            showLoading("")
            presenter.loadCreditRepaymentUrlRequest()
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_REPAYMENT,"")
        }
    }

    override fun initData() {
        showLoading("")
        presenter.loadCreditRepaymentDataRequest()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
            requireContext().sendBroadcast(intent)

            presenter.loadCreditRepaymentDataRequest()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化列表
     */
    private fun initRecyclerView() {
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        val topDecoration = App.dp2px(20f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        mLableAdapter = CreditRepaymentLableAdapter(binding.recyclerView)
        binding.recyclerView.adapter = mLableAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        mLableAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        })
    }

    /**
     * 添加侧边菜单
     */
    private fun addMenuFragment(){
        childFragmentManager
            .beginTransaction()
            .add(R.id.menuLayout, UserFragment(binding.drawerLayout)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * 收起
     */
    private fun showOpenOrCloseView(){
        if (isOpen){//展开
            binding.recyclerView.visibility = View.VISIBLE
            binding.vLine.visibility = View.VISIBLE
            binding.ivLable.setImageResource(R.mipmap.pic_up_gray_icon)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_OPEN,"")
        } else {
            binding.recyclerView.visibility = View.GONE
            binding.vLine.visibility = View.GONE
            binding.ivLable.setImageResource(R.mipmap.pic_down_gray_icon)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_CLOSE,"")
        }
    }

    /**
     * 设置还款信息
     */
    override fun showRepaymentData(data: JSONObject) {
        binding.tvAmount.text = data.optString("amount")
        binding.tvRepayAmount.text = data.optString("repayAmount")
        binding.tvRepayDate.text = data.optString("repayDate")
        binding.tvTotalRepayAmount.text = data.optString("repayAmount") + " " + data.optString("currency")

        val jsArray = data.optJSONArray("repayList")
        val dataList = arrayListOf<JSONObject>()
        if (jsArray != null) {
            for (i in 0..<jsArray.length()){
                dataList.add(jsArray.optJSONObject(i))
            }
        }
        mLableAdapter!!.data = dataList
    }

    /**
     * 设置还款url
     */
    override fun setRepaymentUrl(repaymentUrl: String) {
        val uri = Uri.parse(repaymentUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    override fun onRequestFinish() {
        super.onRequestFinish()
        hideLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_REPAYMENT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_REPAYMENT_END,"")
    }
}